﻿namespace UFIDA.U9.Cust.HWProject.CreateARBill
{
    using System;
    using System.Collections.Generic;
    using System.Text;
    using UFIDA.U9.Base;
    using UFIDA.U9.ISV.AR;
    using UFSoft.UBF.AopFrame;
    using UFSoft.UBF.PL.Engine.Cache;
    using UFSoft.UBF.Transactions;
    using UFSoft.UBF.Util.Context;

    /// <summary>
    /// CreateARBill partial 
    /// </summary>	
    public partial class CreateARBill
    {
        internal BaseStrategy Select()
        {
            return new CreateARBillImpementStrategy();
        }
    }

    #region  implement strategy	
    /// <summary>
    /// Impement Implement
    /// 
    /// </summary>	
    internal partial class CreateARBillImpementStrategy : BaseStrategy
    {
        public CreateARBillImpementStrategy() { }

        public override object Do(object obj)
        {
            CreateARBill bpObj = (CreateARBill)obj;
            if (bpObj == null)
            {
                return null;
            }
            using (UBFTransactionScope scope = new UBFTransactionScope(TransactionOption.RequiresNew))
            {
                OutDtoData outDto = new OutDtoData();
                try
                {
                    long OrgID = Context.LoginOrg.ID;
                    string OrgCode = Context.LoginOrg.Code;
                    string OrgName = Context.LoginOrg.Name;
                    //应收外部立账服务BP
                    UFIDA.U9.ISV.AR.Proxy.CreateImportARBillSVProxy createImportARBillSVProxy = new ISV.AR.Proxy.CreateImportARBillSVProxy();
                    createImportARBillSVProxy.ImportARBillHeadDTOs = new List<ISV.AR.ImportARBillHeadDTOData>();

                    foreach (InnDtoData innDto in bpObj.Data)
                    {

                        #region 创建应收单头
                        ISV.AR.ImportARBillHeadDTOData importARBillHeadDTO = new ISV.AR.ImportARBillHeadDTOData();

                        //业务组织
                        importARBillHeadDTO.BizOrg = new CBO.Pub.Controller.CommonArchiveDataDTOData();
                        importARBillHeadDTO.BizOrg.Code = OrgCode;
                        importARBillHeadDTO.BizOrg.ID = OrgID;
                        importARBillHeadDTO.BizOrg.Name = OrgName;

                        //单据类型
                        if (string.IsNullOrEmpty(innDto.DocumentType))
                        {
                            throw new Exception("单据类型为必传项");
                        }
                        importARBillHeadDTO.DocumentType = new CBO.Pub.Controller.CommonArchiveDataDTOData();
                        importARBillHeadDTO.DocumentType.Code = innDto.DocumentType;

                        //立账日期
                        if (string.IsNullOrEmpty(innDto.AccrueDate))
                        {
                            innDto.AccrueDate = DateTime.Now.Date.ToString("yyyy-MM-dd");
                        }
                        importARBillHeadDTO.AccrueDate = Convert.ToDateTime(innDto.AccrueDate);

                        if (string.IsNullOrEmpty(innDto.AccrueCust))
                        {
                            throw new Exception("客户编码为必选项");
                        }
                        //客户
                        UFIDA.U9.CBO.SCM.Customer.Customer customer = CBO.SCM.Customer.Customer.Finder.Find(string.Format("Code='{0}' and Org.ID='{1}'", innDto.AccrueCust, OrgID));
                        if (customer == null)
                        {
                            throw new Exception("未找到对应客户");
                        }
                        importARBillHeadDTO.PayCust = new CBO.SCM.Customer.CustomerMISCInfoData();
                        importARBillHeadDTO.PayCust.Code = customer.Code;
                        importARBillHeadDTO.AccrueCust = new CBO.SCM.Customer.CustomerMISCInfoData();
                        importARBillHeadDTO.AccrueCust.Code = customer.Code;

                        importARBillHeadDTO.DocStatus = 2;

                        //币种
                        if (string.IsNullOrEmpty(innDto.AC))
                        {
                            innDto.AC = customer.PayCurrency.Code;
                        }
                        importARBillHeadDTO.AC = new CBO.Pub.Controller.CommonArchiveDataDTOData();
                        importARBillHeadDTO.AC.Code = innDto.AC;


                        //来源单据号
                        if (string.IsNullOrEmpty(innDto.SrcDocNo))
                        {
                            importARBillHeadDTO.DescFlexField.PrivateDescSeg1 = innDto.SrcDocNo;
                        }

                        #endregion
                        importARBillHeadDTO.ImportARBillLineDTOs = new List<ISV.AR.ImportARBillLineDTOData>();
                        


                        #region 创建应收单行
                        foreach (InnDtoInfoData item in innDto.ARBillLine)
                        {
                            ISV.AR.ImportARBillLineDTOData DocLine = new ISV.AR.ImportARBillLineDTOData();

                            //料品
                            if (string.IsNullOrEmpty(item.ItemCode))
                            {
                                throw new Exception("料号为必传项");
                            }
                            UFIDA.U9.CBO.SCM.Item.ItemMaster itemMaster = CBO.SCM.Item.ItemMaster.Finder.Find(string.Format("Code='{0}' and Org.ID='{1}'", item.ItemCode, OrgID));
                            if (itemMaster == null)
                            {
                                throw new Exception("未找到对应料品");
                            }
                            DocLine.Item = new CBO.SCM.Item.ItemInfoData();
                            DocLine.Item.ItemCode = itemMaster.Code;
                            DocLine.Item.ItemID = itemMaster.ID;
                            //行数量默认为1
                            DocLine.PUAmount = 1;
                            

                            //税组合
                            DocLine.TaxSchedule = new CBO.Pub.Controller.CommonArchiveDataDTOData();
                            if (itemMaster.SaleInfo.SaleTaxSchedule == null)
                            {
                                throw new Exception("对应料品未找到税组合，请维护");
                            }
                            DocLine.TaxSchedule.Code = itemMaster.SaleInfo.SaleTaxSchedule.Code;
                            DocLine.TaxSchedule.ID = itemMaster.SaleInfo.SaleTaxSchedule.ID;

                            DocLine.IsIncludeTax = customer.IsTaxPrice;


                            //未税价格
                            //  DocLine.UnitPrice = item.TaxPrice * (1 - itemMaster.SaleInfo.SaleTaxSchedule.TaxScheduleTaxs[0].Tax.TaxRate);
                            DocLine.UnitPrice = item.TaxPrice;
                           // DocLine.Money = item.TaxPrice;
                            //DocLine.Money = item.TaxPrice * (1-itemMaster.SaleInfo.SaleTaxSchedule.TaxScheduleTaxs[0].Tax.TaxRate);

                            DocLine.DescFlexField = new Base.FlexField.DescFlexField.DescFlexSegmentsData();
                            DocLine.DescFlexField.PrivateDescSeg1 = item.OldSODocNo;
                            DocLine.DescFlexField.PubDescSeg4 = item.Shop;
                            DocLine.DescFlexField.PrivateDescSeg2 = item.Reason;
                            importARBillHeadDTO.ImportARBillLineDTOs.Add(DocLine);
                        }
                        #endregion
                        createImportARBillSVProxy.ImportARBillHeadDTOs.Add(importARBillHeadDTO);
                    }
                    List<ImportARBillResultDTOData> resultDTODatas = createImportARBillSVProxy.Do();
                    if (resultDTODatas == null)
                    {
                        throw new Exception("未能成功创建数据");
                    }
                    foreach (ImportARBillResultDTOData item in resultDTODatas)
                    {
                        if (!string.IsNullOrEmpty(item.DocNO))
                        {
                            OutDtoInfoData outDtoInfo = new OutDtoInfoData();
                            outDtoInfo.ARBillDocNo = item.DocNO;
                            outDtoInfo.Message = "添加成功";
                            outDto.Data.Add(outDtoInfo);
                        }
                        #region 提交
                        UFIDA.U9.AR.ForTI.Proxy.ARBillSubmitForTISVProxy submit = new AR.ForTI.Proxy.ARBillSubmitForTISVProxy();
                        submit.ARBillHeadKey = item.ID;
                        submit.Do();
                        #endregion
                        PLCacheManager.DataCache.FlushCache();
                        PLCacheManager.ObjectCache.FlushCache();	
                        #region 审核
                        UFIDA.U9.AR.ForTI.Proxy.ARBillApproveForTISVProxy approve = new AR.ForTI.Proxy.ARBillApproveForTISVProxy();
                        approve.ARBillHeadKey = item.ID;
                        approve.Do();
                        #endregion
                    }
                }
                catch (Exception e)
                {
                    outDto.Code = "Error";
                    outDto.Msg = "创建失败 原因是" + e.Message;
                    //失败
                    scope.Rollback();
                    return outDto;
                }
                outDto.Code = "OK";
                outDto.Msg = "创建成功";
                //成功
                scope.Commit();
                return outDto;
            }

        }
    }
}

#endregion
